<template>
    <div v-loading="loading" style="width: 100%;">
        <SavePage :title="`${typeName}${form.month ? form.month + '月份' : form.quarter + '季度'}养护计划`">
            <template slot="buttons">
                <BaseButton :loading="submitLoading" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips title="基本信息" :required="true" />
                <el-form ref="form" :model="form" class="size-auto" :rules="rules" :inline="true" size="medium" label-width="86px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="公路" prop="roadCode">
                                <el-select v-model="form.roadCode" disabled placeholder="请选择" @change="getRoadName">
                                    <el-option
                                        v-for="item in roadOptions"
                                        :key="item.code"
                                        :label="item.name"
                                        :value="item.code"
                                        style="width: 100%"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="制表" prop="tabulation">
                                <el-input v-if="type === 'change' || !!change" v-model="form.tabulationName" disabled />
                                <el-select v-else v-model="form.tabulation" placeholder="请选择">
                                    <el-option
                                        v-for="item in userOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        style="width: 100%"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="负责人" prop="principal">
                                <el-input v-if="type === 'change' || !!change" v-model="form.principalName" disabled />
                                <el-select v-else v-model="form.principal" placeholder="请选择">
                                    <el-option
                                        v-for="item in userOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="上级批复" prop="higherPrincipal">
                                <el-input v-if="type === 'change' || !!change" v-model="form.higherPrincipalName" disabled />
                                <el-select v-else v-model="form.higherPrincipal" placeholder="请选择">
                                    <el-option
                                        v-for="item in superLevelUserOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>             
                </el-form>
                <EverydayForm ref="everydayForm" :form.sync="everydayForm" :project-options="everydayProjectOptions" :rules="everydayRules" />
                <SpecialForm ref="specialForm" :form.sync="specialForm" :project-options="specialProjectOptions" :rules="specialRules" />
            </template>
        </SavePage>
    </div>
</template>

<script>
import { isNumber2 } from '@/utils/validate'
import { OrgModel, RoadPlanModel, RoadModel } from '@/models' 
import EverydayForm from './components/EverydayForm'
import SpecialForm from './components/SpecialForm'
import { uniqueId } from 'lodash-es'

export default {
    name: 'StandingBookAdd',
    components: {
        EverydayForm,
        SpecialForm
    },
    data() {
        return {
            loading: true,
            model: new RoadPlanModel(),
            roadModel: new RoadModel(),
            orgModel: new OrgModel(),
            form: {
                roadCode: null,
                tabulation: null,
                principal: null,
                higherPrincipal: null,
                planType: 2, // 计划类型 1-年度计划，2-季度计划，3-月度计划
                recordType: 1 // 记录类型 1-计划，2-变更 （默认为1）
            },
            everydayForm: {
                dailyList: [{ budgetMoney: null, uid: uniqueId() }]
            },
            specialForm: {
                specialList: [{ uid: uniqueId() }]
            },
            everydayRules: {
                workAmount: [{ validator: this.validNum, trigger: 'blur' }],
                projectId: [{ validator: (rule, value, callback) => (this.validMoney(rule, value, callback, 1)), trigger: 'change' }]
            },
            specialRules: {
                prepareCompletionMoney: [{ validator: this.validNum, trigger: 'blur' }],
                projectId: [{ validator: (rule, value, callback) => (this.validMoney(rule, value, callback, 2)), trigger: 'change' }]
            },
            rules: {
                roadCode: [{ required: true, message: '请选择公路', trigger: 'change' }],
                tabulation: [{ required: true, message: '请选择制表', trigger: 'change' }],
                principal: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                higherPrincipal: [{ required: true, message: '请选择上级批复', trigger: 'change' }]
            },
            roadOptions: [],
            userOptions: [],
            superLevelUserOptions: [],
            defalutUserId: null,
            number: null,
            type: 'add',
            queryData: {}, // 查询费用列表的参数
            typeName: '新建',
            typeMap: {
                2: {
                    everyday: 'getEverydayQuarterEditDetail',
                    special: 'getSpecialQuarterEditDetail'
                },
                3: {
                    everyday: 'getEverydayMonthEditDetail',
                    special: 'getSpecialMonthEditDetail'
                }
            },
            everydayProjectOptions: [],
            specialProjectOptions: [],
            submitLoading: false,
            change: null
        }
    },
    async created() {
        this.getQuery()
        this.setRules()
        if (this.type === 'edit' || this.type === 'change') {
            await this.getDetail()
        }
        if (this.type === 'edit') {
            this.getEverydayDetail(this.typeMap[this.form.planType].everyday)
            this.getSpecialDetail(this.typeMap[this.form.planType].special)
        }
        // 查公路列表，然后根据code查highway名字给后端
        await this.getRoadList()
        this.getRoadName(this.form.roadCode)

        this.setQueryData()
        this.getEverydayProjectList()
        this.getSpecialProjectList()
        this.getUserByOrg(this.defalutUserId || this.form.tabulation)
        this.getSuperLevelUser(this.defalutUserId || this.form.tabulation)
    },
    methods: {
        setRules() {
            // 如果month存在说明是月度的，月度不需要做重复性验证，删除；季度要做重复性验证
            if (this.form.month) {
                this.form.planType = 3
                delete this.everydayRules['projectName']
                delete this.everydayRules['projectName']
            } else {
                this.form.planType = 2
            }
        },
        setQueryData() {
            this.queryData = {
                year: this.form.year,
                quarter: this.form.quarter,
                month: this.form.month,
                roadCode: this.form.roadCode,
                planType: this.form.planType - 1 // 计划类型 1-年度，2-季度，3-月度
            }
        },
        // 获取日常养护项目下拉列表
        getEverydayProjectList() {
            this.model.getEverydayProjectList(this.queryData).then(res => {
                const list = res.list.filter(item => (item && item.projectName))
                const options = list.map(item => {
                    return {
                        ...item,
                        value: item.id,
                        label: item.projectName
                    }
                })
                this.everydayProjectOptions = options
            })
        },
        // 获取专项工程项目下拉列表
        getSpecialProjectList() {
            this.model.getSpecialProjectList(this.queryData).then(res => {
                const list = res.list.filter(item => (item && item.projectName))
                const options = list.map(item => {
                    return {
                        ...item,
                        value: item.id,
                        label: item.projectName
                    }
                })
                this.specialProjectOptions = options
            })
        },
        getRoadName(val) {
            this.roadOptions.some(item => {
                if (val === item.code) {
                    this.form.highwayName = item.name
                    // 后端需要添加路段长度、管养机构orgId和orgDept参数
                    this.form.routeLength = item.totalLength
                    this.form.orgId = item.orgId
                    this.form.orgDept = item.orgDept
                    return true
                }
            })
        },
        getRoadList() {
            return this.roadModel.getList({}, { pageSize: 1000 }).then(res => {
                this.roadOptions = res.list.map(item => {
                    return {
                        code: item.highwayCode,
                        name: item.highwayName,
                        totalLength: item.totalLength,
                        orgId: item.sysManagementOrgId,
                        orgDept: item.sysManagementOrgName
                    }
                })
            })
        },
        getQuery() {
            this.type = this.$route.query.type
            this.number = this.$route.query.number
            // 新增时，需要parentNumber上级的number参数
            this.form.parentNumber = this.number
            // 编辑时需要当前number参数
            this.form.number = this.number

            this.form.year = this.$route.query.year
            this.form.quarter = this.$route.query.quarter
            this.form.month = this.$route.query.month
            if (this.type === 'edit') {
                this.typeName = '编辑'
                this.recordType = this.$route.query.recordType || null
            } else if (this.type === 'add') {
                this.typeName = '新建'
                // 新增时，当前用户默认为制表人
                this.defalutUserId = this.$store.getters.avatar.id
                this.form.roadCode = this.$route.query.roadCode
            } else if (this.type === 'change') {
                this.typeName = '变更'
                this.recordType = this.$route.query.recordType || null
            }
            console.log(this.recordType)
        },
        getDetail() {
            return this.model.detail({ number: this.number, planType: this.form.planType }).then(res => {
                this.form = res
                this.form.recordType = this.recordType
            })
        },
        // 获取日常费用详情，年度、季度和月度根据传入的name请求不同接口
        getEverydayDetail(name) {
            this.model[name]({ number: this.number, recordType: this.recordType }).then(res => {
                this.everydayForm.dailyList = res.list.map(item => {
                    return {
                        ...item,
                        uid: uniqueId()
                    }
                })
            })
        },
        // 获取专项工程费用详情，年度、季度和月度根据传入的name请求不同接口
        getSpecialDetail(name) {
            this.model[name]({ number: this.number, recordType: this.recordType }).then(res => {
                this.specialForm.specialList = res.list.map(item => {
                    return {
                        ...item,
                        uid: uniqueId()
                    }
                })
            })
        },
        validNum(rule, value, callback) {
            if (value && !isNumber2(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        },
        validMoney(rule, value, callback, type) {
            if (value) {
                // 判断创建多条时是否重复
                // 查询当前选中数据在数组中是否多于2条，如果是，则说明重复选择了
                let list = []
                if (type === 1) {
                    list = this.everydayForm.dailyList
                } else if (type === 2) {
                    list = this.specialForm.specialList
                }
                const result = list.filter(item => item.projectId === value)
                if (result.length > 1) {
                    callback(new Error('项目选择重复'))
                    return
                }

                // 查询该项目是否有预算费用
                let options = []
                if (type === 1) {
                    options = this.everydayProjectOptions
                } else if (type === 2) {
                    options = this.specialProjectOptions
                }
                options.some(item => {
                    if (item.id === value) {
                        if (!item.budgetMoney) {
                            callback(new Error('无此项目费用预算'))
                        } else {
                            callback()
                        }
                        return true
                    }
                })
            } else {
                callback()
            }
        },
        validCost(rule, value, callback) {
            // 查询当前选中数据在数组中是否多于2条，如果是，则说明重复选择了
            const result = this.everydayForm.dailyList.filter(item => item.costName === value)
            console.log(result)
            if (result.length > 1) {
                callback(new Error('不能重复选择相同费用'))
            } else {
                callback()
            }
        },
        validProject(rule, value, callback) {
            // 查询当前选中数据在数组中是否多于2条，如果是，则说明重复选择了
            const result = this.specialForm.specialList.filter(item => item.projectName === value)
            if (result.length > 1) {
                callback(new Error('不能重复选择相同费用'))
            } else {
                callback()
            }
        },
        submit() {
            this.submitLoading = true
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const res1 = await this.$refs['everydayForm'].handleValidate()
                    const res2 = await this.$refs['specialForm'].handleValidate()
                    if (res1 && res2) {
                        const form = JSON.parse(JSON.stringify(this.form))
                        // 如果是变更，planType季度还是月度在上面处理了，加上当前变更changeId，删除原id
                        if (this.type === 'change') {
                            form.changeId = form.id
                            delete form.id
                        }
                        const data = { 
                            ...form,
                            ...this.everydayForm,
                            ...this.specialForm
                        }
                        this.model.saveOrUpdate(data).then(() => {
                            this.$message({
                                type: 'success',
                                message: this.type === 'edit' ? '修改成功！' : '新建成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        }).finally(() => {
                            this.submitLoading = false
                        })
                    } else {
                        this.submitLoading = false
                    }
                } else {
                    this.submitLoading = false
                }
            })
        },
        // 获取机构下人员
        getUserByOrg(id) {
            this.loading = true
            this.orgModel.getUserByOrg({ userId: id }).then(res => {
                this.userOptions = res.map(item => {
                    // 如果是新增，把负责人一项默认值设置为当前部门负责人
                    if (this.type === 'add' && item.isPrincipal) {
                        this.form.principal = item.userId
                    }
                    return {
                        value: item.userId,
                        label: item.name
                    }
                })
                // 把制表默认值设置为当前登录用户
                this.type === 'add' && (this.form.tabulation = id)
            }).finally(() => {
                this.loading = false
            })
        },
        // 根据当前用户查询上级部门用户
        getSuperLevelUser(id) {
            this.loading = true
            this.orgModel.getSuperLevelUser({ userId: id }).then(res => {
                this.superLevelUserOptions = res.map(item => {
                    // 如果是新增，把负责人一项默认值设置为当前部门负责人
                    if (this.type === 'add' && item.isPrincipal) {
                        this.form.higherPrincipal = item.userId
                    }
                    return {
                        value: item.userId,
                        label: item.name
                    }
                })
            }).finally(() => {
                this.loading = false
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.el-form--inline.size-auto.width-100 {
    ::v-deep {
        // form的label-width：72px 根据实际label宽度修改
        .el-form-item__content {
            width: calc(100% - 100px);
        }
    }    
}
.margin-b-0 {
    margin-bottom: 0;
}
.add-box {
    width: 100%;
    height: 40px;
    line-height: 40px;
    margin-bottom: 24px;
    background: rgb(250, 250, 250);
    border: 1px solid #F5F7FA;
    border-radius: 5px;
    text-align: center;
    cursor: pointer;
    &:hover {
        background: rgb(240, 240, 240);
    }
    i {
        color: #171725;
        font-style: normal;
    }
}
</style>
